package booksystem.controller;

import booksystem.dao.AdminDao;
import booksystem.dao.BookDao;
import booksystem.dao.OrderDao;
import booksystem.dao.UserDao;
import booksystem.dao.impl.AdminDaoImpl;
import booksystem.dao.impl.BookDaoImpl;
import booksystem.dao.impl.OrderDaoImpl;
import booksystem.dao.impl.UserDaoImpl;
import booksystem.entity.Admin;
import booksystem.entity.Book;
import booksystem.entity.Order;
import booksystem.entity.User;
import booksystem.utils.MD5Utils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@WebServlet(name = "AdminServlet", urlPatterns = "/admin")
public class AdminServlet extends BaseServlet {
    private AdminDao adminDao = new AdminDaoImpl();
    private UserDao userDao = new UserDaoImpl();
    private BookDao bookDao = new BookDaoImpl();
    private OrderDao orderDao = new OrderDaoImpl();

    /*
     * 管理员登录
     * */
    public void adminLogin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 获取参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String code = req.getParameter("code");
        // 2. 处理业务
        // 根据 username 和 password 到数据库查询
        String pwd = MD5Utils.md5(password);
//        System.out.println(pwd);
        Admin loginAdmin = adminDao.adminLogin(username, pwd);
        // 3. 返回响应内容
        HttpSession session = req.getSession();
        String session_code = (String) session.getAttribute("code");
        // 3.1 如果登录成功，请求转发到main.jsp, 否则重定向到login.jsp
        if (loginAdmin != null && code.toUpperCase().equals(session_code.toUpperCase())) {
            // 将username共享在session中，便于main.jsp显示用户信息
            // 会话属性
            session.setAttribute("id", loginAdmin.getId());
            session.setAttribute("admin_username", loginAdmin.getUsername());
            // 请求属性
            req.setAttribute("id", loginAdmin.getId());
            req.setAttribute("admin_username", loginAdmin.getUsername());
            // 请求转发共用一个请求对象
//            req.getRequestDispatcher("/main.jsp").forward(req, resp);
            //响应重定向，不能共用request对象，但共用session对象
            resp.sendRedirect("/admin?m=userList");
        } else {
            resp.sendRedirect("/admin_login.jsp");
        }
    }

    /*
     * 获取用户列表
     * */
    public void userList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        if (session.getAttribute("admin_username") == null) {
            resp.sendRedirect("/admin_login.jsp");
        } else {
            // 获取全部用户信息
            List<User> user_list = userDao.getAllUser();
            // 将订单信息传到前端页面
            req.setAttribute("list", user_list);
            req.getRequestDispatcher("/admin/user_manage.jsp").forward(req, resp);
        }
    }

    /*
     * 获取图书列表
     * */
    public void bookList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        if (session.getAttribute("admin_username") == null) {
            resp.sendRedirect("/admin_login.jsp");
        } else {
            // 获取全部图书信息
            List<Book> book_list = bookDao.getAllBook();
            // 将订单信息传到前端页面
            req.setAttribute("list", book_list);
            req.getRequestDispatcher("/admin/book_manage.jsp").forward(req, resp);
        }

    }

    /*
     * 获取订单列表
     * */
    public void orderList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        if (session.getAttribute("admin_username") == null) {
            resp.sendRedirect("/admin_login.jsp");
        } else {
            // 获取全部图书信息
            List<Order> order_list = orderDao.getAllOrder();
            List<String> book_name = new ArrayList<>();
            List<String> username = new ArrayList<>();
            // 获取图书名称、用户昵称
            for (Order order : order_list) {
                // 通过订单中的book_id 获取book表中的书籍信息
                Book book = bookDao.getBookDetail(order.getBook_id());
                book_name.add(book.getName());
                User user = userDao.getUser(order.getUser_id());
                username.add(user.getUsername());
            }
            // 将订单信息传到前端页面
            req.setAttribute("list", order_list);
            req.setAttribute("book_name", book_name);
            req.setAttribute("user_name", username);
            req.getRequestDispatcher("/admin/order_manage.jsp").forward(req, resp);
        }
    }


    /*
     * 删除用户接口
     * */
    public void deleteUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        if (session.getAttribute("admin_username") == null) {
            resp.sendRedirect("/admin_login.jsp");
        } else {
            // 获取订单号
            String user_id = req.getParameter("uid");
            // 执行删除操作
            userDao.deleteUser(user_id);
//            userList(req, resp);
            resp.sendRedirect("/admin?m=bookList");
        }

    }


    /*
     * 删除图书接口
     * */
    public void deleteBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        if (session.getAttribute("admin_username") == null) {
            resp.sendRedirect("/admin_login.jsp");
        } else {
            // 获取订单号
            String book_id = req.getParameter("bid");
            // 执行删除操作
            bookDao.deleteBook(book_id);
//            bookList(req, resp);
            resp.sendRedirect("/admin?m=bookList");
        }
    }

    /*
     * 删除订单接口
     * */
    public void deleteOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        if (session.getAttribute("admin_username") == null) {
            resp.sendRedirect("/admin_login.jsp");
        } else {
            // 获取订单号
            String order_id = req.getParameter("oid");
            // 执行删除操作
            orderDao.deleteOrder(order_id);
//            orderList(req, resp);
            resp.sendRedirect("/admin?m=orderList");
        }
    }

    /*
     * 添加图书接口
     * */
    public void addBookInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, IllegalAccessException {
        HttpSession session = req.getSession();
        if (session.getAttribute("admin_username") == null) {
            resp.sendRedirect("/admin_login.jsp");
        } else {
            // 获取传递的图书信息
            Map<String, String[]> params = req.getParameterMap();
            Book book = new Book();
            // BeanUtils只能自动处理String类型, 如果属性里有非字符串类型的属性，需要注册转换器
            ConvertUtils.register(new Converter() {
                @Override
                public Object convert(Class aClass, Object o) {
                    if (o == null)
                        return null;
                    if (o instanceof String) {
                        String temp = (String) o;
                        if ("".equals(temp))
                            return null;
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        try {
                            return sdf.parse(temp);
                        } catch (ParseException e) {
                            e.printStackTrace();
                            return null;
                        }
                    }
                    return null;
                }
            }, Date.class);
            BeanUtils.populate(book, params);
//            System.out.println(book.getClassify());
            int a = bookDao.saveBook(book);
//            bookList(req, resp);
            resp.sendRedirect("/admin?m=bookList");
        }

    }

    /*
     * 管理员退出登录
     * */
    public void adminLogout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 用户退出登录，销毁session对象
        HttpSession session = req.getSession();
        session.invalidate();
        // 删除cookie
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie : cookies) {
            cookie.setMaxAge(0);
            cookie.setPath("/");
            resp.addCookie(cookie);
        }
        resp.sendRedirect("/admin_login.jsp");
    }

}
